import re

from utils.common_import import *
from config.prometheus_metric import PrometheusMetric

class Mount(Resource):
    @exception_response()
    def get(self):
        node_total = cluster_client.prometheus_client.query(PrometheusMetric.NODE_SYSTEM_SIZE_TOTAL)
        mount_info = {}
        if "data" in node_total and "result" in node_total["data"]:
            for item in node_total["data"]["result"]:
                node = item["metric"]["instance"].split(":")[0]
                mountpoint = re.sub("^/rootfs", "", item["metric"]["mountpoint"]) or "/"

                device = item["metric"]["device"]

                mount_info.setdefault(node, {})
                mount_info[node][mountpoint] = dict(
                                  device=device,
                                  mountpoint=mountpoint,
                                  node=node,
                                  size=item["value"][1])

        node_free  = cluster_client.prometheus_client.query(PrometheusMetric.NODE_SYSTEM_SIZE_AVAIL)
        if "data" in node_free and "result" in node_free["data"]:
            for item in node_free["data"]["result"]:
                node = item["metric"]["instance"].split(":")[0]
                mountpoint = re.sub("^/rootfs", "", item["metric"]["mountpoint"]) or "/"

                mount_info[node][mountpoint]["avail"] = item["value"][1]
                mount_info[node][mountpoint]["used"] = (1 - float(mount_info[node][mountpoint]["avail"])/float(mount_info[node][mountpoint]["size"]))*100


        mount_info_list = []
        for node in mount_info:
            for mountpoint in mount_info[node]:
                mount_info_list.append(mount_info[node][mountpoint])

        return make_success_response(mount_info_list)